package com.whjz.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectUtil {
    /**
     * 调用方法
     */
    public static Object invoke(Method method, Object obj, Object... args) throws InvocationTargetException, IllegalAccessException {
        boolean accessible = method.isAccessible();
        method.setAccessible(true);
        Object result;
        try {
            result = method.invoke(obj, args);
        } finally {
            method.setAccessible(accessible);
        }
        return result;
    }

    /**
     * 获取值
     */
    public static Object getField(Field field, Object obj) throws IllegalAccessException {
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        Object result;
        try {
            result = field.get(obj);
        }finally {
            field.setAccessible(accessible);
        }
        return result;
    }

    /**
     * 设置值
     */
    public static void setField(Field field, Object obj, Object value) throws IllegalAccessException {
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        try {
            field.set(obj, value);
        }finally {
            field.setAccessible(accessible);
        }
    }
}
